﻿import kliment.display.loader.LoaderAbstract;
import kliment.display.MCC;
import kliment.events.ErrorEvent;
import kliment.events.Event;
import kliment.events.HTTPStatusEvent;
import kliment.events.ProgressEvent;
import mx.utils.Delegate;

/**
 * ...
 * @author	Kliment
 * @version	2.2.8
 */

class kliment.display.loader.MCLoader extends LoaderAbstract {
	private var CONTAINER_NAME:String = "loadedCell";
	private var _updteProgressDalay:Number = 30;
	private var _mcLoader:MovieClipLoader;
	private var _intervalID:Number;
	private var _target_mc:MovieClip;
	
	public function MCLoader(target_mc:MovieClip, url:String) {
		super(target_mc);
		
		_mcLoader = new MovieClipLoader();
		if (url)
			load(url);
	}
	
	public function load(url:String):Boolean {
		super.load(url);
		_mcLoader.addListener(_getListener());
		var result:Boolean = _mcLoader.loadClip(url, _target_mc);
		return result;
	}
	
	private function _getListener():Object {
		var listener:Object = new Object();
		listener.onLoadStart = Delegate.create(this, _onLoadStartHandler);
		listener.onLoadComplete = Delegate.create(this, _ononLoadCompleteHandler);
		listener.onLoadInit = Delegate.create(this, _onLoadInitHandler);
		listener.onLoadError = Delegate.create(this, _onLoadErrorHandler);
		return listener;
	}
	
	private function _onLoadStartHandler(target_mc:MovieClip):Void {
		_target_mc = target_mc;
		_intervalID = setInterval(this, '_onLoadProgressHandler', _updteProgressDalay, _mcLoader, _target_mc);
		dispatchEvent(new Event(Event.OPEN, this));
		_onLoadProgressHandler(_mcLoader, _target_mc);
	}
	
	private function _onLoadProgressHandler(mcLoader:MovieClipLoader, target_mc:MovieClip):Void {
		_progressInfo = mcLoader.getProgress(target_mc);
		dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, this, _progressInfo.bytesLoaded, _progressInfo.bytesTotal));
	}
	
	private function _ononLoadCompleteHandler(target_mc:MovieClip, httpStatus:Number):Void {
		clearInterval(_intervalID);
		_onLoadProgressHandler(_mcLoader, _target_mc);
		dispatchEvent(new HTTPStatusEvent(HTTPStatusEvent.HTTP_STATUS, this, httpStatus));
		dispatchEvent(new Event(Event.COMPLETE, this));
	}
	
	private function _onLoadInitHandler(target_mc:MovieClip):Void {
		_isLoadInit = true;
		dispatchEvent(new Event(Event.INIT, this));
	}
	
	private function _onLoadErrorHandler(target_mc:MovieClip, errorCode:String, httpStatus:Number):Void {
		dispatchEvent(new HTTPStatusEvent(HTTPStatusEvent.HTTP_STATUS, this, httpStatus));
		dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, this, errorCode));
	}
	
	public function toString():String {
		return "[MCLoader target_mc=" + _target_mc + "]";
	}
	
	public function remove():Void {
		clearInterval(_intervalID);
		_mcLoader.unloadClip(_target_mc);
		super.remove();
	}
	
	public function get target_mc():MovieClip { return _target_mc; }
	
}